package cn.lkp.mall.search.impl;

import cn.lkp.common.to.es.SkuEsModel;
import cn.lkp.common.utils.R;
import cn.lkp.mall.search.config.ESConfig;
import cn.lkp.mall.search.constant.EsConstant;
import cn.lkp.mall.search.feign.ProductFeignService;
import cn.lkp.mall.search.service.MallSearchService;
import cn.lkp.mall.search.vo.AttrResponseVo;
import cn.lkp.mall.search.vo.BrandRespVo;
import cn.lkp.mall.search.vo.SearchParam;
import cn.lkp.mall.search.vo.SearchResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MallSearchServiceImpl implements MallSearchService {
    @Autowired
    private RestHighLevelClient client;
    @Autowired
    ProductFeignService productFeignService;

    @Override
    public SearchResult search(SearchParam param) {
        SearchResult result = null;
        SearchRequest searchRequest = buildSearchRequest(param);
        try {
            SearchResponse response = client.search(searchRequest, ESConfig.COMMON_OPTIONS);
            result = buildSearchResult(response, param);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    private SearchRequest buildSearchRequest(SearchParam param) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (!StringUtils.isEmpty(param.getKeyword())) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", param.getKeyword()));
        }
        if (param.getCatalog3Id() != null) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        }
        if (param.getBrandId() != null && param.getBrandId().size() > 0) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        }
        if (param.getHasStock() != null) {
            boolQuery.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1));
        }
        /**
         * 价格区间
         * 1_500/_500/500_
         * "range":{
         *     "skuPrice": {
         *         "gte": 0,
         *         "lte": 6000
         *     }
         * }
         */
        if (!StringUtils.isEmpty(param.getSkuPrice())) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] s = param.getSkuPrice().split("_");
            if (s.length == 2) {
                rangeQuery.gte(s[0]).lte(s[1]);
            } else if (s.length == 1) {
                if (param.getSkuPrice().startsWith("_")) {
                    rangeQuery.lte(s[0]);
                }
                if (param.getSkuPrice().endsWith("_")) {
                    rangeQuery.gte(s[0]);
                }
            }
            boolQuery.filter(rangeQuery);
        }

        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            //attr=1_6寸：8寸&attr=2_8G:16G
            for (String attrStr : param.getAttrs()) {
                BoolQueryBuilder nestedboolQuery = QueryBuilders.boolQuery();
                String[] s = attrStr.split("_");
                String attrId = s[0];
                String[] attrValues = s[1].split(":");
                nestedboolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedboolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedboolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }
        sourceBuilder.query(boolQuery);
        //比如排序sort中的价格排序skuPrice_asc/desc
        if (!StringUtils.isEmpty(param.getSort())) {
            String sort = param.getSort();
            String[] s = sort.split("_");
            SortOrder order = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(s[0], order);
        }

        sourceBuilder.from((param.getPageNum() - 1) * EsConstant.PAGE_SIZE);

        sourceBuilder.size(EsConstant.PAGE_SIZE);

        if (!StringUtils.isEmpty(param.getKeyword())) {
            //搜索关键字时才高亮
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color: red'>");
            highlightBuilder.postTags("</b>");
            sourceBuilder.highlighter(highlightBuilder);
        }
        //品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg").field("brandId").size(50);
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        sourceBuilder.aggregation(brand_agg);
        //分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        ;
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        sourceBuilder.aggregation(catalog_agg);
        //属性聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        attr_agg.subAggregation(attr_id_agg);
        sourceBuilder.aggregation(attr_agg);

        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);
        return searchRequest;
    }

    private SearchResult buildSearchResult(SearchResponse response, SearchParam param) {
        SearchResult result = new SearchResult();
        SearchHits hits = response.getHits();
        List<SkuEsModel> esModels = new ArrayList<>();
        if (hits.getHits() != null && hits.getHits().length > 0) {
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel esModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                if (!StringUtils.isEmpty(param.getKeyword())) {
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String s = skuTitle.fragments()[0].string();
                    esModel.setSkuTitle(s);
                }
                esModels.add(esModel);
            }
        }
        result.setProducts(esModels);

        ParsedLongTerms catalog_agg = response.getAggregations().get("catalog_agg");
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        for (Terms.Bucket bucket : catalog_agg.getBuckets()) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            String catalogId = bucket.getKeyAsString();
            catalogVo.setCatalogId(Long.parseLong(catalogId));
            //打断点调试发现实际返回的aggregations类型是其间接子类ParsedStringTerms,
            //所以将catalog_name_agg的类型设置为ParsedStringTerms
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            String catalogName = catalog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalogName);
            catalogVos.add(catalogVo);
        }
        result.setCatalogs(catalogVos);
        //当前所有商品涉及到的所有属性信息
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            //得到属性的id
            long attrId = bucket.getKeyAsNumber().longValue();
            attrVo.setAttrId(attrId);
            //得到属性的名字
            String attrName = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
            //List<String> attrValues = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets().stream().map(MultiBucketsAggregation.Bucket::getKeyAsString).collect(Collectors.toList());
            //得到属性的所有值
            List<String> attrValues = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets().stream().map(item -> {
                String keyAsString = item.getKeyAsString();
                return keyAsString;
            }).collect(Collectors.toList());
            attrVo.setAttrName(attrName);
            attrVo.setAttrValue(attrValues);
            attrVos.add(attrVo);
        }
        result.setAttrs(attrVos);

        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            long brandId = bucket.getKeyAsNumber().longValue();
            brandVo.setBrandId(brandId);
            ParsedStringTerms brand_img_agg = bucket.getAggregations().get("brand_img_agg");
            String brandImg = brand_img_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandImg);
            ParsedStringTerms brand_name_agg = bucket.getAggregations().get("brand_name_agg");
            String brandName = brand_name_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);
            brandVos.add(brandVo);
        }
        result.setBrands(brandVos);

        result.setPageNum(param.getPageNum());
        long total = hits.getTotalHits().value;
        result.setTotal(total);
        int totalPages = (int) (total) % EsConstant.PAGE_SIZE == 0 ? (int) (total) % EsConstant.PAGE_SIZE : ((int) (total) % EsConstant.PAGE_SIZE + 1);
        result.setTotalPages(totalPages);
        //构建检索响应结果的分页导航功能
        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPages; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);

        //构建属性的面包屑导航功能
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            List<SearchResult.NavVo> attrNavVos = param.getAttrs().stream().map(attr -> {
                SearchResult.NavVo attrNavVo = new SearchResult.NavVo();
                //attr为1_5寸：6寸
                String[] s = attr.split("_");
                attrNavVo.setNavValue(s[1]);
                //需要根据attrId查attrName,所以调用远程商品服务
                try{
                    R r = productFeignService.attrInfo(Long.parseLong(s[0]));
                    //将当前属性id加入专门放置已选中属性的集合
                    result.getAttrIds().add(Long.parseLong(s[0]));
                    if (r.getCode() == 0) {
                        //由于R工具类中原先的方法是将map(key为data)转换成AttrRespVo返回，而调用的商品服务方法中存的key是attr,因此在R中定义一个新方法，传一个可作为key的字符串,将map转成对象返回。
                        //检索模块中没有AttrRespVo这个类，并且他继承了AttrVo,所以需要将这两个类拷贝到公共模块，或将他们合二为一，拷贝到检索模块并改名为AttrResponseVo。
                        //这样就按照key为attr,返回检索模块自己的AttrResponseVo
                        AttrResponseVo attrResponseVo = r.getData("attr", new TypeReference<AttrResponseVo>(){});
                        attrNavVo.setNavName(attrResponseVo.getAttrName());
                    } else {
                        attrNavVo.setNavName(s[0]);
                    }
                }catch(Exception e){
                }
                String replace = replaceQueryString(param, attr,"attrs");
                attrNavVo.setLink("http://search.mall.com/list.html?"+replace);
                return attrNavVo;
            }).collect(Collectors.toList());
            result.setNavs(attrNavVos);
        }

        //品牌加入面包屑导航功能
        if(param.getBrandId() !=null && param.getBrandId().size()>0){
            SearchResult.NavVo brandNavVo = new SearchResult.NavVo();
            //取出result中的navs
            List<SearchResult.NavVo> navs = result.getNavs();
            brandNavVo.setNavName("品牌");
            //远程查询所有品牌
            try{
                R infos = productFeignService.brandInfo(param.getBrandId());
                if(infos.getCode()==0){
                    List<BrandRespVo> brands = infos.getData("brand", new TypeReference<List<BrandRespVo>>() {
                    });
                    StringBuffer buffer = new StringBuffer();
                    String replace = "";
                    for (BrandRespVo brand : brands) {
                        buffer.append(brand.getName()+";");
                        replace = replaceQueryString(param,brand.getBrandId()+"","brandId");
                    }
                    brandNavVo.setNavValue(buffer.toString());
                    brandNavVo.setLink("http://search.mall.com/list.html?"+replace);
                }
            }catch(Exception e){}
            //添加brandNavVo到result
            navs.add(brandNavVo);
        }

        //TODO 分类也加入面包屑导航功能，不需要取消导航

        return result;
    }

    private String replaceQueryString(SearchParam param, String value, String key) {
        //取消了面包屑导航后，应该去掉当前取消掉的面包屑导航条件，进行页面跳转。相当于更改地址栏字符串，在controller中比较容易修改
        String encode = null;
        try {
            //解决地址栏中文编码问题
            encode = URLEncoder.encode(value, "UTF-8");
            encode = encode.replace("+","%20");//浏览器对空格编码处理和Java不一样
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //将编码后的地址进行字符串替换
        String replace = param.get_queryString().replace("&"+key+"=" + encode, "");
        return replace;
    }

}
